package com.kuang.easyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.kuang.easyexcel.config.DemoDataListener;
import com.kuang.easyexcel.pojo.Excel;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class uploadController {

    /**
     * 文件上传
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link Excel}
     * <p>
     * 2. 由于默认一行行的读取excel，所以需要创建excel一行一行的回调监听器，参照{@link DemoDataListener}
     * <p>
     * 3. 直接读即可
     */
    @RequestMapping("/upload")
    @ResponseBody
    @CrossOrigin
    public String upload(@RequestPart("file") MultipartFile file) throws IOException {
        //EasyExcel.read(file.getInputStream(), Excel.class, new DemoDataListener()).sheet().doRead();
        EasyExcel.read(file.getInputStream(), Excel.class, new DemoDataListener()).sheet().doRead();
        return "success";
    }

    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link Excel}
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("设备台账", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Excel.class).sheet("模板").doWrite(data());
    }

    /**
     * 打印数据
     *
     * @return
     */
    private List<Excel> data() {
        List<Excel> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Excel data = new Excel();
            data.setDevice_code("设备" + i);
            data.setCard_date(new Date());
            data.setDevice_size(String.valueOf(0.56));
            list.add(data);
        }
        return list;
    }

    /**
     * 填充excel
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/download2")
    public void download2(HttpServletResponse response) {
        try {
            //设置HTTP响应的内容类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //设备在字符类型
            response.setCharacterEncoding("utf-8");
            //下载的文件名
            String fileName = URLEncoder.encode("错误台账", "UTF-8").replaceAll("\\+", "%20");
            //设置响应头
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //加载模板
            ClassPathResource templateResource = new ClassPathResource("templates/xxx.xlsx");
            //写入数据
            EasyExcel.write(response.getOutputStream())
                    .withTemplate(templateResource.getInputStream())
                    .sheet()
                    .doFill(data());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
